import Dexie from 'dexie'
class MyDataBase extends Dexie {
  constructor (dbName) {
    super(dbName)
    this.version(1).stores({
      firstTable: '++favoriteId, url_f, name_f, type_f,description_f,data_s',
      titleTxtTable: '++id,name'
    })
  }
}

let db
export function initDB (dbName) {
  db = new MyDataBase(dbName)
  console.log('数据库创建成功!')
}
/**
 * @param {*} tableName
 * @zs 查询某一个表中的所有的数据
 */

export async function searchDB (tableName) {
  let data
  switch (tableName) {
    case 'WT':
      data = await db.titleTxtTable.toArray()
      break
    case 'FT':
      data = await db.firstTable.toArray()
      break
    default:
      throw new Error('Unknown table name: ' + tableName)
  }
  return data
}

/**
 *
 * @param {int} id
 * @param {String} tableName
 * @returns
 * @zs 查询某个表中的某条数据
 */
export async function searchTableDB (id, tableName) {
  let data
  switch (tableName) {
    case 'WT':
      data = await db.titleTxtTable.where({ favoriteId: id }).first()
      break
    case 'FT':
      data = await db.firstTable.where({ favoriteId: id }).first()
      break
    default:
      throw new Error('Unknown table name: ' + tableName)
  }
  return data
}

export async function addDB (data, tableName) {
  switch (tableName) {
    case 'WT':
      db.titleTxtTable
        .where('name')
        .equals(data.name)
        .first() // 注意：这里的 first() 是 Dexie Table 对象的方法
        .then(async result => {
          if (result) {
            console.log('找到了目标--WT')
          } else {
            console.log('没有找到匹配的记录--WT')
            await db.titleTxtTable.add(data)
          }
        })
        .catch(error => {
          console.error('查询出错:', error)
        })
      break
    case 'FT':
      db.titleTxtTable
        .where('name_f')
        .equals(data.name_f)
        .first() // 注意：这里的 first() 是 Dexie Table 对象的方法
        .then(async result => {
          if (result) {
            console.log('找到目标--WT')
          } else {
            console.log('没有找到匹配的记录--WT')
            await db.firstTable.add(data)
          }
        })
        .catch(error => {
          console.error('查询出错:', error)
        })
      break
    default:
      throw new Error('Unknown table name: ' + tableName)
  }
}
